using UnityEngine;
using System.Collections;


public class AnimationController : MonoBehaviour {
	
	public int keyBindSize = 0;
	public int idleAnimationSize = 3;
	
	public string[] idleAnimation;
	public float[] idleModeDuration;

	public KeyCode[] keyBind;
	public string[] animationBind;
	public WrapMode[] animationWrapMode;
	public float[] animationSpeed;
	
	//for checking if there is last key release in one group's keys
	public int[] keyReleaseGroup;
	
	protected bool isIdle = true;
	protected float idleModeChangingTime;
	protected int idleMode = 0;
	
	bool isStopIdleAnim = false;
	
	
	virtual protected void Start () {
		
		animation.Play(idleAnimation[0]);
		animation[idleAnimation[0]].wrapMode = WrapMode.Loop;
		UpdateAnimationData();
		print(gameObject.GetComponent<AnimationControllerIOS>());
		
	}
	
	// Update is called once per frame
	virtual protected void Update () {
		UpdateAnimationData();
		UpdateAnimaiton();
		UpdateIdle();
	}
	protected void UpdateAnimationData()
	{
		for(int i = 0;i<keyBindSize;i++)
		{
			UnityEngine.AnimationState state = animation[animationBind[i]];
			//set wrapMode from list
			state.wrapMode = animationWrapMode[i];
			state.speed = animationSpeed[i];
		}
	}
	virtual protected void UpdateAnimaiton()
	{
		
		for(int i = 0;i<keyBindSize;i++)
		{
			UnityEngine.AnimationState state = animation[animationBind[i]];
			
			
			if(Input.GetKeyDown(keyBind[i]))
			{
				isIdle = false;
				animation.Blend(animationBind[i]);
			}
			else if(Input.GetKeyUp(keyBind[i]) && isKeyTheLastUp(i))
			{
				//if wrapMode is Loop, stop it
				if(state.wrapMode == WrapMode.Loop)
				{
					isIdle = true;
				}
			}
		}
	}
	
	protected void UpdateIdle()
	{
		if(isIdle)
		{
			isStopIdleAnim = false;
			idleModeChangingTime += Time.deltaTime;
			//if over the duration of that idle animation , change it
			if(idleModeChangingTime > idleModeDuration[idleMode])
			{
				idleMode = (idleMode + 1) % idleAnimationSize;
				idleModeChangingTime = 0;
			}
			animation.CrossFade(idleAnimation[idleMode]);
		//	animation.Blend(idleAnimation[idleMode]);
		} else {
			// need to stop to avoid the problem of other animation!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
			for (int i = 0; !isStopIdleAnim && i < idleAnimation.Length; i++)
				animation.Stop(idleAnimation[i]);
			isStopIdleAnim = true;
		}
	}
	
	protected bool isKeyTheLastUp(int index)
	{
		int thisKeyGroup = keyReleaseGroup[index];
		
		for(int i = 0;i < keyBindSize;i++)
		{
			//if the same keygroup
			if(thisKeyGroup == keyReleaseGroup[i] && Input.GetKey(keyBind[i]))
			{
				return false;
			}
		}
		return true;
	}
	
	
}
